package com.tc.service.impl;

import com.tc.dto.Login;
import com.tc.dto.Result;
import com.tc.factory.ResultFactory;
import com.tc.mapper.LoginMapper;
import com.tc.myDto.UserApp;
import com.tc.service.LoginService;
import com.tc.utils.Json;
import com.tc.utils.SetWeChatServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SetWeChatServer weChatServer;
    @Autowired
    private ResultFactory result;
    @Autowired
    private Json json;
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private ExecutorService executorService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public Result login(Login login) {
        //获取openid与sessionKey并转成Map集合
        Map<String,String> map=json.parseStr(weChatServer.getOpenIdAndSessionKey(login));
        //定义用户
        UserApp userApp;
        //首先判断openid是否存在,不存在则存储
        if(loginMapper.check(map.get("openid"))==null){
            //给user对象配置openid与sessionKey,再添加到数据库
            login.getUser().setOpenId(map.get("openid"));
            login.getUser().setSessionKey(map.get("session_key"));
            loginMapper.addWXUser(login.getUser());
            //然后获取当前数据的主键id
            userApp=loginMapper.selectOpenId(map.get("openid"));
            //把id转为String类型
            String s=String.valueOf(userApp.getId());
            //直接将添加添加任务交给线程池,减少响应耗时
            executorService.execute(()->{
                //并且将openId永久存入redis,并且与主键id关联
                redisTemplate.opsForValue().set(s,map.get("openid"));
            });
        }else{
            //此时说明openid存在，则根据openid查询查询id
            userApp=loginMapper.selectOpenId(map.get("openid"));
        }
        //封装并返回openid与主键id,以及用户基本信息
        List<String> list=new ArrayList<>();
        list.add(map.get("openid"));
        list.add(String.valueOf(userApp.getId()));
        list.add(userApp.getNickName());
        list.add(userApp.getAvatarUrl());
        return result.success(list);
    }
}
